//
//  UITextView_Extension.swift
//  EmotiDemo
//
//  Created by leador on 17/5/17.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit

extension UITextView {
    
    ///获取textView属性字符串，所对应的表情字符
    func getEmoticonString()->String {
        
        let attMutableStr = NSMutableAttributedString (attributedString: attributedText)
        
        let attRange = NSRange(location: 0, length: attMutableStr.length)
        attMutableStr.enumerateAttributes(in: attRange, options: []) { (dict, range, _) in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                
                attMutableStr.replaceCharacters(in: range, with: attachment.chs!)
                
            }
        }
        
        return attMutableStr.string
        
    }
    
    ///给TextView插入表情
    func insertEmoticon(emoticon:Emoticon) {
        
        if emoticon.isEmpty {
            return
        }
        
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        if emoticon.emojiCode != nil {
            let textRange = selectedTextRange!
            replace(textRange, withText: emoticon.emojiCode!)
            return
        }
        
        let attachment = EmoticonAttachment()
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        attachment.chs = emoticon.chs
        let fon = font!
        attachment.bounds = CGRect(x: 0, y: -4, width: fon.lineHeight, height: fon.lineHeight)
        let attImageStr = NSAttributedString(attachment: attachment)
        
        let attTextStr = NSMutableAttributedString(attributedString: attributedText)
        let textRange = selectedRange
        attTextStr.replaceCharacters(in: textRange, with: attImageStr)
        
        attributedText = attTextStr
        
        //将文字的大小重置
        font = fon
        
        //将光标设置到原来的位置加1
        selectedRange = NSRange(location: textRange.location+1, length: 0)
        
    }

    
}
